/**
 @文件名： index
 @来源：YongPing.Wang|2023/11/18 17:03
 @描述：皮肤
 **/
import LGLog from '@/config/common/log.ts'
import { getUuidUnit } from '@/units/jsUnits.ts'

const distPath: string = `/static/skin/`

// 使用路径引入css
function loadCSSPath(path: string): void {
  const head = document.getElementsByTagName('head')[0]
  const linkId = `skinLGId`
  const linkEle = document.getElementById(linkId)
  if (linkEle) linkEle.parentNode?.removeChild(linkEle)
  const skinCssEle = document.createElement('link')
  skinCssEle.href = `${path}?v=${getUuidUnit()}-${__APP_VERSION__}`
  skinCssEle.rel = 'stylesheet'
  skinCssEle.type = 'text/css'
  skinCssEle.setAttribute('id', linkId)
  head.appendChild(skinCssEle)
}

// dev模式下获取皮肤
async function getDevSkin(skinKey: string): Promise<boolean> {
  const reg = /.*skin\/(.*)\/index\.css/
  const modules = import.meta.glob('@/theme/skin/*/index.css', { as: 'url' })
  for (const key of Object.keys(modules)) {
    const regMatch = key.match(reg)
    if (!regMatch) continue
    const skinKeyGet = regMatch[1] || ''
    if (skinKeyGet !== skinKey) continue
    // 找到真实的url路径
    const path = await modules[key]()
    loadCSSPath(path)
  }
  return true
}

// prod模式下获取皮肤
async function getProdSkin(skinKey: string): Promise<boolean> {
  const reqUrl = `${distPath}${skinKey}/index.css`
  loadCSSPath(reqUrl)
  return true
}

// 切换皮肤调用函数
export async function renderSkin(skinKey: string): Promise<boolean> {
  let data: boolean = false
  if (import.meta.env.DEV) {
    data = await getDevSkin(skinKey)
  } else {
    data = await getProdSkin(skinKey)
  }
  LGLog.capsule('设置皮肤', 'defaultSkin')
  return data
}
